﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Net;
using System.IO;
using System.Windows.Forms;
using System.Data;

namespace CDDocumentExtractor
{
    class Program
    {
        private static string _juridiction = "1";
        public static string Juridiction { get
            {
                //if (_juridiction == "SC")
                //    return "1";
                //else if (_juridiction == "HC")
                //    return "2";

                return _juridiction;
            } 
            set { _juridiction = value; }
        }

        private static string _courtNameId = "4";   //4 is for supreme court
        public static string CourtNameId
        {
            get
            {
                return _courtNameId;
            }
            set { _courtNameId = value; }
        }

        private static string _courtName = "DEL";   //Name of Court
        public static string CourtName
        {
            get
            {
                return _courtName;
            }
            set { _courtName = value; }
        }

        private static string _documentFolderYear= "102000";   //Name of Court
        public static string DocumentFolderYear
        {
            get
            {
                return _documentFolderYear;
            }
            set { _documentFolderYear  = value; }
        }

        static void Main(string[] args)
        {

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new frmManuFileProcessor());
            Application.EnableVisualStyles();
            return;
            //int flag = 0;

            //try
            //{
            //    if (args.Length>0)
            //    {
            //        flag = int.Parse(args[0]);
            //    }

            //    //var files123 = Directory.GetFiles(WebUtility.SourceFolder, "PROCESSED_MANU*.txt");
            //    //var tempFile = WebUtility.TempFile.Replace(".htm", ".csv");
            //    //if (File.Exists(tempFile))
            //    //    File.Delete(tempFile);

            //    //File.WriteAllText(tempFile, "");
            //    //foreach (var item in files123)
            //    //{
            //    //    Console.WriteLine(item);
            //    //    var data = File.ReadAllText(item);
            //    //    var links = Common.GetTags("a", data);
            //    //    foreach (var link in links)
            //    //    {
            //    //        System.Text.RegularExpressions.Regex rxManuID = new System.Text.RegularExpressions.Regex("MANU\\x2F\\w*\\x2F\\d*\\x2F\\d{4}", System.Text.RegularExpressions.RegexOptions.IgnoreCase | System.Text.RegularExpressions.RegexOptions.Singleline);
            //    //        File.AppendAllText(tempFile, Path.GetFileName(item).Replace(".txt", "").Replace("PROCESSED_", "").Replace('/', '_') + "*" + System.Text.RegularExpressions.Regex.Replace(link, "<.*?>", string.Empty).Replace(' ', '_') + "*" + rxManuID.Match(link).Value.Trim() + Environment.NewLine);
            //    //    }
            //    //}

            //    //////return;

            //    if (flag == 0 || flag == 1)
            //    {
            //        Directory.CreateDirectory(WebUtility.ArchieveFolder);
            //        var files = Directory.GetFiles(WebUtility.SourceFolder, "MANU*.txt");
            //        int i = 1;

            //        Console.WriteLine("Converting files. Total Files to Convert : " + files.Length.ToString());
            //        foreach (var item in files)
            //        {
            //            //var ffffName = Path.GetFileName(item);
            //            //if (File.Exists(Path.Combine(WebUtility.ArchieveFolder, ffffName)))
            //            //{
            //            //    continue;
            //            //}

            //            Console.WriteLine(item);
            //            var data = File.ReadAllText(item);
            //            try
            //            {
            //                CaseDocument cd = new CaseDocument(data);
            //                try
            //                {
            //                    Console.WriteLine("Save Start : " + i.ToString());
            //                    bool result = cd.Save();
            //                    Console.WriteLine("Save Complete");
            //                    if (result)
            //                    {
            //                        //Move the file to a different name
            //                        File.Move(item, Path.Combine(WebUtility.ArchieveFolder, Path.GetFileName(item)));

            //                        //Write Updated File at this location with removed information
            //                        //This is only required if Link parsing should be done
            //                        //If resulting file doesn't contatins any link this step is not required
            //                        if (cd.LinkParsingRequired)
            //                        {
            //                            File.WriteAllText(
            //                                Path.Combine(WebUtility.SourceFolder, "PROCESSED_" + Path.GetFileName(item)),
            //                                cd.InfoOneDocumentData);
            //                        }

            //                        File.AppendAllText(WebUtility.DocumentLogFile,
            //                                           cd._ManuID + "," + cd.DocumentID.ToString() + "," + cd._Title +
            //                                           "," + cd._DecidedOn.ToShortDateString() + "," + "Completed" +
            //                                           Environment.NewLine);

            //                        Console.WriteLine(cd._ManuID);
            //                    }
            //                }
            //                catch (Exception ex)
            //                {
            //                    if (ex.Message.Contains("Cannot add an entity "))
            //                    {
            //                        //Move the file to a different name
            //                        File.Move(item, Path.Combine(WebUtility.ArchieveFolder, Path.GetFileName(item)));
            //                    }
            //                    File.AppendAllText(WebUtility.DocumentLogFile,
            //                                       cd._ManuID + "," + cd.DocumentID.ToString() + "," + cd._Title + "," +
            //                                       cd._DecidedOn.ToShortDateString() + "," + ex.Message + "," +
            //                                       ex.StackTrace + Environment.NewLine);
            //                }
            //            }
            //            catch (Exception ex1)
            //            {
            //                Console.WriteLine(ex1.Message + "***" + ex1.StackTrace);
            //            }
            //            i++;
            //        }
            //        Console.WriteLine("Done... Converting files");
            //    }

                
            //    Console.WriteLine("");
            //    Console.WriteLine("");

            //    if (flag == 0 || flag == 2)
            //    {
            //        Console.WriteLine("Generating InfoOne Citation Nos.");
            //        try
            //        {
            //            Common.GenerateAndUpdateInfoOneCitationNos();
            //        }
            //        catch (Exception ex)
            //        {
            //            Console.WriteLine(ex.Message);
            //            Console.WriteLine("*************");
            //            Console.WriteLine(ex.StackTrace);
            //            return;
            //        }
            //        Console.WriteLine("Done... Generating InfoOne Citation Nos.");
            //    }

            //    Console.WriteLine("");
            //    Console.WriteLine("");

            //    if (flag == 0 || flag == 3)
            //    {
            //        Console.WriteLine("Processing Links in the Documents");
            //        Common.ParseLinksInDocument();
            //        Console.WriteLine("Done... Processing Links in the Documents");

            //        Console.WriteLine("Creating Document PDF files from Section Files");
            //        Common.CreateDocumentPDFs(Path.Combine(WebUtility.DocumentsFolder,
            //                                               "PublishedDocs/" + WebUtility.DocumentsYear));
            //        Console.WriteLine("Done... Creating Document PDF files from Section Files");
            //    }
            //    Console.WriteLine("");
            //}
            //catch (Exception ex)
            //{
            //    Console.WriteLine(ex.Message);
            //    Console.WriteLine("*************");
            //    Console.WriteLine(ex.StackTrace);
            //    Console.ReadLine();
            //}
            ////Console.ReadLine();
            //return;
            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new MDIParent());

            ////HttpWebResponse response;
            ////StringBuilder sb = new StringBuilder();

            ////for (int i = 100581; i < 100582; i++)
            ////{
            ////    if (Request_www_manupatra_com(i.ToString(), out response))
            ////    {
            ////        // Gets the stream associated with the response.
            ////        Stream receiveStream = response.GetResponseStream();
            ////        Encoding encode = System.Text.Encoding.GetEncoding("utf-8");

            ////        // Pipes the stream to a higher level stream reader with the required encoding format. 
            ////        StreamReader readStream = new StreamReader(receiveStream, encode);

            ////        Char[] read = new Char[256];
            ////        // Reads 256 characters at a time.    
            ////        int count = readStream.Read(read, 0, 256);

            ////        while (count > 0)
            ////        {
            ////            // Dumps the 256 characters on a string and displays the string to the console.
            ////            String str = new String(read, 0, count);
            ////            //Console.Write(str);
            ////            sb.Append(str);
            ////            count = readStream.Read(read, 0, 256);
            ////        }

            ////        if (sb.ToString().Contains("<manuid>"))
            ////        {
            ////            Console.WriteLine("File Written");
            ////            System.IO.File.AppendAllText(@"C:\aaa.txt", sb.ToString());
            ////        }
            ////        //clear string
            ////        sb.Remove(0, sb.Length - 1);


            ////        // Releases the resources of the Stream.
            ////        readStream.Close();

            ////        //Success, possibly use response.
            ////        response.Close();
            ////    }
            ////    else
            ////    {
            ////        //Failure, cannot use response.
            ////    }
            ////}

            ////Console.ReadLine();
        }

        public static void UpdateDocumentInformation()
        {
            using (Db4objects.Db4o.IObjectContainer db = DataAccess.GetDataContainer())
            {
                string manuid = "<manuid\\b[^>]*>(.*?)</manuid>";
                System.Text.RegularExpressions.Regex rx = new System.Text.RegularExpressions.Regex(manuid, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                string title = "<title\\b[^>]*>(.*?)</title>";
                System.Text.RegularExpressions.Regex rxtitle = new System.Text.RegularExpressions.Regex(title, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                string decidedon = "<decidedon\\b[^>]*>(.*?)</decidedon>";
                System.Text.RegularExpressions.Regex rxdecidedon = new System.Text.RegularExpressions.Regex(decidedon, System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                string subject = "<subject\\b[^>]*>(.*?)</subject>";
                System.Text.RegularExpressions.Regex rxsubject = new System.Text.RegularExpressions.Regex(subject, System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                List<DocumentsToDownload> list = db.Query<DocumentsToDownload>().ToList();
                Console.WriteLine(list.Count.ToString() + " Total Documents");

                if (list.Count > 0)
                {
                    int commitCount = 0;
                    string _ManuID = "";
                    string _Title = "";
                    string _DecidedOn = "";
                    //string _Subject = "";

                    foreach (var item in Directory.GetFiles(@"c:\InfoOneSourceDocuments", "*.txt", SearchOption.TopDirectoryOnly))
                    {
                        commitCount++;
                        string documentData = File.ReadAllText(item);

                        //Get Manu id from the document
                        var manuidMatch = rx.Match(documentData);
                        var titleMatch = rxtitle.Match(documentData);
                        var decidedonMatch = rxdecidedon.Match(documentData);
                        //var subjectMatch = rxsubject.Match(documentData);

                        _ManuID = System.Text.RegularExpressions.Regex.Replace(manuidMatch.Value, "<.*?>", string.Empty);
                        _Title = System.Text.RegularExpressions.Regex.Replace(titleMatch.Value, "<.*?>", string.Empty);
                        _DecidedOn = System.Text.RegularExpressions.Regex.Replace(decidedonMatch.Value, "<.*?>", string.Empty);
                        //_Subject = System.Text.RegularExpressions.Regex.Replace(subjectMatch.Value, "<.*?>", string.Empty);

                        Console.WriteLine(_ManuID);
                        var doc = list.Find(d => _Title.StartsWith(d.DocumentTitle.Trim()) && d.DecidedOn.Equals(_DecidedOn));
                        //    (delegate(DocumentsToDownload d)
                        //{
                        //    return _Title.StartsWith(d.DocumentTitle.Trim()) && d.DecidedOn.Trim() == _DecidedOn && d.Subject.Trim() == _Subject;
                        //}).FirstOrDefault();

                        if (doc != null)
                        {
                            doc.ManuID = _ManuID;
                            doc.Downloaded = true;
                            db.Store(doc);
                        }

                        if (commitCount == 1000)
                        {
                            //Commit on every hundred records to keep transaction short
                            db.Commit();
                            commitCount = 0;
                        }
                    }
                    db.Commit();
                }
                db.Close();
            }
        }

        /// <summary>
        /// Tries to request the URL: http://www.manupatra.com/NXT/gateway.dll/sc/supreme2001/sc2010/s100920.htm
        /// </summary>
        /// <param name="response">After the function has finished, will possibly contain the response to the request.</param>
        /// <returns>True if the request was successful; false otherwise.</returns>
        public static bool Request_www_manupatra_com(string docNumber, out HttpWebResponse response)
        {
            response = null;

            try
            {
                //Create request to URL.
                //HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://www.manupatra.com/NXT/gateway.dll/sc/supreme2001/sc2010/s" + docNumber  + ".htm");

                //Set request headers.

                //request.Accept = "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/msword, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, */*";
                /*request.Referer = "http://www.manupatra.com/latest/Newstab.aspx";
                request.Headers.Set(HttpRequestHeader.AcceptLanguage, "en-us");
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; QS 4.2.4.0; QS 5.1.2.1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; FDM; QS 4.2.4.0; QS 5.1.2.1; .NET4.0C; .NET4.0E; MS-RTC LM 8)";
                request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip, deflate");
                request.Headers.Set(HttpRequestHeader.Cookie, @"__utma=21732263.1795951994.1288761579.1289224314.1289368998.5; __utmz=21732263.1288761579.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=21732263.1.10.1289368998; __utmc=21732263; nxt/gateway.dll/uid=59FFE516; ASP.NET_SessionId=suflbvntpfz41pm5hkt1ph34; ASPSESSIONIDSSCRQTDA=DLIHCFABMPLIBOJLHAEBNABI; NXT/gateway.dll/NPUSERNAME=User7; NXT/gateway.dll/NPPASSWORD=useraug16kgkd; NXT/gateway.dll/NPAC_CREDENTIALSPRESENT=TRUE; nxt/gateway.dll/sid=787BCBEC; nxt/gateway.dll/npac_ticket=%40lrSwi2cMbSUQF5y5jo%2FsDA%3D%3D%3AUser-NamecUser7%26expirationc63425068203; nxt/gateway.dll/npusername=; nxt/gateway.dll/nppassword=; nxt/gateway.dll/npac_credentialspresent=");
                */


                HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:49152/NXT/gateway.dll/Manupatra/sc/2001-2003SC/sc2010/s" + docNumber + ".htm");
                ///NXT/gateway.dll/Manupatra/sc/2001-2003SC/sc2010
                request.UserAgent = "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; QS 4.2.4.0; QS 5.1.2.1; Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) ; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729; FDM; QS 4.2.4.0; QS 5.1.2.1; .NET4.0C; .NET4.0E; MS-RTC LM 8)";
                request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
                request.Headers.Set(HttpRequestHeader.AcceptLanguage, "en-us,en;q=0.5");
                request.Headers.Set(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
                request.Headers.Set(HttpRequestHeader.AcceptCharset, "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
                request.Headers.Add("Keep-Alive", "300");
                request.KeepAlive = true;
                request.Referer = "http://localhost:49152/NXT/gateway.dll/Manupatra/sc/2001-2003SC/sc2010/index.html?fn=document-frameset.htm&f=templates&uq=1$force=1778";
                //request.Headers.Set(HttpRequestHeader.Cookie, @"nxt/gateway.dll/uid=7DB6062A; nxt/gateway.dll/sid=7DB6062B");
                request.Headers.Set(HttpRequestHeader.Cookie, @"__utma=21732263.1795951994.1288761579.1289224314.1289368998.5; __utmz=21732263.1288761579.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utmb=21732263.1.10.1289368998; __utmc=21732263; nxt/gateway.dll/uid=59FFE516; ASP.NET_SessionId=suflbvntpfz41pm5hkt1ph34; ASPSESSIONIDSSCRQTDA=DLIHCFABMPLIBOJLHAEBNABI; NXT/gateway.dll/NPUSERNAME=User7; NXT/gateway.dll/NPPASSWORD=useraug16kgkd; NXT/gateway.dll/NPAC_CREDENTIALSPRESENT=TRUE; nxt/gateway.dll/sid=787BCBEC; nxt/gateway.dll/npac_ticket=%40lrSwi2cMbSUQF5y5jo%2FsDA%3D%3D%3AUser-NamecUser7%26expirationc63425068203; nxt/gateway.dll/npusername=; nxt/gateway.dll/nppassword=; nxt/gateway.dll/npac_credentialspresent=");


                //Get response to request.
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException e)
            {
                //ProtocolError indicates a valid HTTP response, but with a non-200 status code (e.g. 304 Not Modified, 404 Not Found)
                if (e.Status == WebExceptionStatus.ProtocolError) response = (HttpWebResponse)e.Response;
                else return false;
            }
            catch (Exception)
            {
                if (response != null) response.Close();
                return false;
            }

            return true;
        }


        public static DataTable GetCourtsJurisdictionData()
        {
            var dt = new DataTable("CourtsJurisdictions");
            dt.Columns.Add("TypeOfCourt", typeof (System.Int32));
            dt.Columns.Add("TypeOfCourtDesc", typeof(System.String));
            dt.Columns.Add("CourtName", typeof(System.String));
            dt.Columns.Add("CourtID", typeof(System.Int32));
            dt.Columns.Add("ShortCode", typeof(System.String));

            var fileToRead = Path.Combine(System.Windows.Forms.Application.StartupPath, "courts.csv");

            var lines = File.ReadAllLines(fileToRead);
            var tt = "";
            try
            {
                foreach (var line in lines)
                {
                    tt = line;
                    var data = line.Split(',');
                    var dr = dt.NewRow();
                    dr[0] = Convert.ToInt32(data[0]);
                    dr[1] = data[1];
                    dr[2] = data[2];
                    dr[3] = Convert.ToInt32(data[3]);
                    dr[4] = data[4];
                    dt.Rows.Add(dr);
                }
            }catch(Exception ex)
            {
                MessageBox.Show(tt);
            }
            return dt;
        }
    }
}
